﻿using System.Web.Services;
using Nomad.WebSync.Extensions;
using Nomad.WebSync.Service.DAO;
using System.Web.Services.Protocols;
using System;
using System.Text;

namespace Nomad.WebSync.Service {
    public partial class Mobile {
        /// <summary>
        /// Creates a new user account
        /// </summary>
        /// <param name="username">Encrypted Username</param>
        /// <param name="password">Encrypted Password</param>
        /// <param name="email">Encrypted E-mail</param>
        [WebMethod(Description = "Creates a new user account")]
        public string CreateAccount(string username, string password, string email) {
            var decryptEmail = email.Decrypt();
            var decryptUsername = username.Decrypt();
            var decryptPassword = password.Decrypt();

            Account.CreateAccount(decryptUsername, decryptPassword, decryptEmail);
            return CreateSession(decryptUsername);
        }

        [WebMethod(Description = "Creates a new user account")]
        public string Login(string username, string password) {
            var decryptPassword = password.Decrypt();
            if (Account.Exists(username, decryptPassword))
                return CreateSession(username);
            else
                return null;
        }

        [SoapHeader("Header"), WebMethod]
        public string GetDeviceID() {
            this.Authentication();
            var account = Account.GetAccountByUser(Header.Username);
            return account.DeviceID;
        }

        [SoapHeader("Header"), WebMethod]
        public void SetDeviceID(string guid) {
            this.Authentication();
            var account = Account.GetAccountByUser(Header.Username);
            account.SetDeviceID(guid);
        }

        [SoapHeader("Header"), WebMethod]
        public void SetOwnerInformation(string information) {
            this.Authentication();
            
            var encryptData = Convert.FromBase64String(information);
            var data = encryptData.Decrypt();

            var name = UnicodeEncoding.Unicode.GetString(data, 0, 72).TrimEnd('\0');
            var company = UnicodeEncoding.Unicode.GetString(data, 72, 72).TrimEnd('\0');
            var address = UnicodeEncoding.Unicode.GetString(data, 144, 372).TrimEnd('\0');
            var phone = UnicodeEncoding.Unicode.GetString(data, 516, 48).TrimEnd('\0');
            var email = UnicodeEncoding.Unicode.GetString(data, 566, 74).TrimEnd('\0');

            var account = Account.GetAccountByUser(Header.Username);
            account.SetOwnerInformation(name, company, address, email, phone);
        }
    }
}
